package cn.ronghuanet.base.exception.handler;

import cn.ronghuanet.base.util.AjaxResult;
import cn.ronghuanet.base.exception.BusinessException;
import cn.ronghuanet.base.exception.ResponseCode;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理类
 * @RestControllerAdvice 它会拦截到所有的controller请求,然后再controller方法执行前和执行后做一些统一的事情
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局处理业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        return AjaxResult.error(e.getMessage(),e.getCode());
    }

    /**
     * 处理jsr303的异常信息
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        // 拿到jsr303的异常信息的值,拼接给前端
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer stringBuffer = new StringBuffer();
        for (ObjectError allError : allErrors) {
            stringBuffer.append(allError.getDefaultMessage());
            stringBuffer.append("!");
        }
        return AjaxResult.error(stringBuffer.toString(), ResponseCode.RESPONSE_CODE_40010.getCode());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.error(ResponseCode.RESPONSE_CODE_500.getMessage(),ResponseCode.RESPONSE_CODE_500.getCode());
    }
}
